﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Threading.Tasks;
using Peter.Common;
using Peter.Common.Interfaces;
using Peter.Common.MainMenu;

namespace Peter.Logic
{
   /// <summary>
   /// A quick open provider for files in the current directory.
   /// </summary>
   [Export (typeof (IQuickOpenProvider))]
   public class CurrentDirectoryQop : IQuickOpenProvider
   {
      /// <summary>
      /// Gets the title of the quick open provider.
      /// </summary>
      public string Title
      {
         get { return "Current Directory"; }
      }

      /// <summary>
      /// Opens the quick open item with the given key.
      /// </summary>
      /// <param name="item">The quick open item to...open...</param>
      /// <returns>The results of the quick open.</returns>
      public QuickOpenResults Open (QuickOpenItem item)
      {
         var file = item.Tag as FileInfo;
         if (file != null)
            return new QuickOpenResults (QuickOpenResultType.OpenInPeter) { FileToOpen = file.FullName };
         return new QuickOpenResults (QuickOpenResultType.Finished);
      }

      /// <summary>
      /// Gets a dictionary of quick open items for quick open to use.
      /// </summary>
      /// <param name="filter">The Quick open filter.</param>
      /// <returns>A dictionary of items.</returns>
      public async Task <IEnumerable <QuickOpenItem>> GetQuickOpenItemsAsync (string filter)
      {
         var items = new Collection<QuickOpenItem> ();
         var doc = this.Peter.ActiveDocument as IPeterFileDocument;
         if (doc != null && doc.FileInfo != null)
         {
            var dirInfo = doc.FileInfo.Directory;
            if (dirInfo != null)
            {
               var file = filter;
               file = "*" + CommonUtilities.MakeValidFileName (file) + "*";
               await Task.Run (() =>
               {
                  var files = dirInfo.GetFiles (file, SearchOption.TopDirectoryOnly);
                  foreach (var f in files)
                  {
                     items.Add (new QuickOpenItem (this)
                     {
                        Key = f.FullName,
                        Text = f.Name,
                        Tag = f,
                        Icon = MainMenuIconConverter.GetIconForFile (f)
                     });
                  }
               });
            }
         }
         return items;
      }

      /// <summary>
      /// Gets the instance of peter.
      /// </summary>
      [Import (typeof (IPeter))]
      public IPeter Peter { get; set; }
   }
}
